﻿using Microsoft.EntityFrameworkCore;
using UnitTest.Data;
using UnitTest.iRepository;
using UnitTest.Model;

namespace UnitTest.Repository;

public class StudentRepository: IStudentRepository
{
    private readonly AppDbContext _dbContext;

    /// <summary>
    /// 通过构造函数实现依赖注入
    /// </summary>
    /// <param name="dbContext"></param>
    public StudentRepository(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<Student> GetById(int id)
    {
        return await _dbContext.Students.FindAsync(id);
    }

    public async Task<int?> Add(Student entity)
    {
         _dbContext.Students.Add(entity);
         await _dbContext.SaveChangesAsync();
         return 1;
    }

    public async Task<int?> Delete(Student entity)
    {
        entity.Status = 0;
        // 这里执行你的数据库操作，例如添加、更新或删除实体
        await _dbContext.SaveChangesAsync();
        return 1;
    }

    public async Task<List<Student>> GetList()
    {
        var res =  _dbContext.Students.ToList();
        return res;
       
    }

    public async Task<int?> Update(Student entity)
    {
        Student student = _dbContext.Students.Find(entity.ID);
        if (student != null)
        {
            student.Name = entity.Name;
            student.Age = entity.Age;
            student.Gender = entity.Gender;
            _dbContext.Entry<Student>(student).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
            return await _dbContext.SaveChangesAsync();
        }
        return 0;
    }
}